package com.lvmama.rhino.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.entity.OrderCondition;
import com.lvmama.rhino.enums.CommonParentType;
import com.lvmama.rhino.pojo.PitPV;
import com.lvmama.rhino.pojo.PositionAnalysis;
import com.lvmama.rhino.pojo.TopicFunnelDataQuery;
import com.lvmama.rhino.pojo.funnel.SpecialTopicFunnelData;
import com.lvmama.rhino.service.PositionAnalysisService;
import com.lvmama.rhino.service.StatisticCodeService;
import com.lvmama.rhino.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author shenlinli
 * @ClassName: SpecialTopicController
 * @Description: 专题相关方法
 * @date 2017年5月19日 下午5:10:38
 */
@Controller
@RequestMapping("specialTopic")
public class SpecialTopicController extends BaseControllerSupport {

    @Autowired
    private PositionAnalysisService positionAnalysisService;
    @Autowired
    StatisticCodeService statisticCodeService;

    @RequestMapping("topicTree")
    public String topicTree(ModelMap model) {
        return "application/specialTopic/topicTree";
    }

    /**
     * @param @param  choose_date
     * @param @param  themeName
     * @param @param  page_currentNum
     * @param @param  page_size
     * @param @return 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     * @Title: getThemeTab
     * @Description: 分页ajax请求专题列表
     */
    @RequestMapping("topicAjaxData")
    @ResponseBody
    public Map<String, Object> getThemeTab(String platform,String chooseTime,
         String themeName, int pageCurrentNum, int pageSize) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 查询日期条件处理
        Map<String, Date> dateMap = getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        // 封装请求参数
        PositionAnalysis positionAnalysisVo = new PositionAnalysis();
        positionAnalysisVo.setStartDate(beginDate);
        positionAnalysisVo.setEndDate(endDate);
        positionAnalysisVo.setName(themeName);
        if (StringUtils.isNotEmpty(platform)) {
            List<String> statisticCodeList = new ArrayList<String>();
            String[] platforms = StringUtils.split(platform,",");
            for(String pf:platforms){
                statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
            }
            positionAnalysisVo.setStatisticCodeList(statisticCodeList);
        }
        positionAnalysisVo.setPage_size(pageSize);
        positionAnalysisVo.setCurrentPage(pageCurrentNum);

        PageInfo<PositionAnalysis> page = positionAnalysisService
                .getTopicList(positionAnalysisVo);

        List<PositionAnalysis> pas = page.getList();

        List<PitPV> pitPVS = positionAnalysisService
                .getAllPitPV(positionAnalysisVo);

        for(PositionAnalysis pa:pas){
            for(PitPV pv:pitPVS){
                if(pv.getCode().equals(pa.getCode())){
                    pa.setOrderAmount(pv.getOrderAmount());
                    pa.setOrderMoney(pv.getOrderMoney());
                    pa.setPayAmount(pv.getPayAmount());
                    pa.setPayMoney(pv.getPayMoney());
                    break;
                }
            }
        }
        for(PositionAnalysis pa:pas){
            if(pa.getOrderMoney()==null){
                pa.setOrderMoney(0d);
            }
            if(pa.getPayMoney()==null){
                pa.setPayMoney(0d);
            }
        }
        Collections.sort(pas,new Comparator<PositionAnalysis>() {
            @Override
            public int compare(PositionAnalysis o1, PositionAnalysis o2) {
                // 返回值为int类型，大于0表示正序，小于0表示逆序
                return o2.getClickNum()-o1.getClickNum();
            }
        });

        page = new PageInfo<>(pas);
        resultMap.put("page", page);
        return resultMap;
    }

    /**
     * 获取主题点击量 曝光量
     *
     * @param chooseTime
     * @param code
     * @return
     */
    @RequestMapping("topicClickData")
    @ResponseBody
    public Map<String, Object> getTopicClickData(String chooseTime, String code,String platform) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 查询日期条件处理
        Map<String, Date> dateMap = getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        // 封装请求参数
        PositionAnalysis positionAnalysisVo = new PositionAnalysis();
        positionAnalysisVo.setStartDate(beginDate);
        positionAnalysisVo.setEndDate(endDate);
        positionAnalysisVo.setCode(code);
        if (StringUtils.isNotEmpty(platform)) {
            List<String> statisticCodeList = new ArrayList<String>();
            String[] platforms = StringUtils.split(platform,",");
            for(String pf:platforms){
                statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
            }
            positionAnalysisVo.setStatisticCodeList(statisticCodeList);
        }
        positionAnalysisVo.setPage_size(10);
        positionAnalysisVo.setCurrentPage(1);
        PageInfo<PitPV> page = positionAnalysisService.getTopicPVByCode(positionAnalysisVo);
        page.getList().remove(page.getList().size()-1);
        resultMap.put("topicPVList", page.getList());
        return resultMap;
    }


    /**
     * 获取主题点击量 曝光量
     *
     * @param chooseTime
     * @param code
     * @return
     */
    @RequestMapping("topicClickAll")
    public String getTopicClickAll(ModelMap model, String chooseTime, String code,String platform, OrderCondition oc) {
        // 查询日期条件处理
        Map<String, Date> dateMap = getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");

        // 封装请求参数
        PositionAnalysis positionAnalysisVo = new PositionAnalysis();
        positionAnalysisVo.setStartDate(beginDate);
        positionAnalysisVo.setEndDate(endDate);
        positionAnalysisVo.setCode(code);
        positionAnalysisVo.setPage_size(oc.getPageSize());
        positionAnalysisVo.setCurrentPage(oc.getPage());
        positionAnalysisVo.setName("tab_name");
        if (StringUtils.isNotEmpty(platform)) {
            List<String> statisticCodeList = new ArrayList<String>();
            String[] platforms = StringUtils.split(platform,",");
            for(String pf:platforms){
                statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
            }
            positionAnalysisVo.setStatisticCodeList(statisticCodeList);
        }
        PageInfo<PitPV> page = positionAnalysisService.getTopicPVByCode(positionAnalysisVo);
        model.addAttribute("page", page);
        model.addAttribute("topicPVList", page.getList());
        model.addAttribute("chooseTime", chooseTime);
        model.addAttribute("code", code);
        model.addAttribute("platform", platform);
        return "application/specialTopic/topicClickDetail";
    }


    /**
     * 图表数据
     *
     * @param code
     * @param chooseTime
     * @return
     * @throws Exception
     */
    @RequestMapping("chartData")
    @ResponseBody
    public Map<String, Object> chartData(@RequestParam("code") String code,
                                         @RequestParam("chooseTime") String chooseTime, String themeName,String platform) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        PositionAnalysis pit = new PositionAnalysis();
        // 查询日期条件处理
        Map<String, Date> dateMap = getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        pit.setStartDate(beginDate);
        pit.setEndDate(endDate);
        pit.setCode(code);
        pit.setName(themeName);
        if (StringUtils.isNotEmpty(platform)) {
            List<String> statisticCodeList = new ArrayList<String>();
            String[] platforms = StringUtils.split(platform,",");
            for(String pf:platforms){
                statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
            }
            pit.setStatisticCodeList(statisticCodeList);
        }
        List<PositionAnalysis> pitListByCategory = positionAnalysisService
                .getPitListByCategory(pit);

        List<PositionAnalysis> pitListByDate = positionAnalysisService
                .getPitListByDate(pit);
        List<PositionAnalysis> pitBarByCategory = positionAnalysisService
                .getPitBarByCategory(pit);

        // 总订单量 总订单金额
        int payAmountTotal = 0;
        double payMoneyTotal = 0;

        // 饼状图数据
        JSONArray payAmountArr = new JSONArray();
        JSONArray payMoneyArr = new JSONArray();
        for (PositionAnalysis positionAnalysis : pitListByCategory) {
            if (positionAnalysis.getPayMoney() == null) {
                continue;
            }
            payAmountTotal += positionAnalysis.getPayAmount();
            payMoneyTotal += positionAnalysis.getPayMoney();
            JSONObject payAmountOb = new JSONObject();
            payAmountOb.put("categoryName", CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
            payAmountOb.put("amount", positionAnalysis.getPayAmount());
            payAmountArr.add(payAmountOb);
            JSONObject payMoneyOb = new JSONObject();
            payMoneyOb.put("categoryName", CommonParentType.getCategoryShowName(positionAnalysis.getCategoryId()));
            payMoneyOb.put("amount", positionAnalysis.getPayMoney());
            payMoneyArr.add(payMoneyOb);
        }
        // 柱状图数据
        List<String> categoryNames = new ArrayList<>();
        JSONArray arr2 = new JSONArray();
        for (PositionAnalysis positionAnalysis : pitBarByCategory) {
            String categoryName = CommonParentType
                    .getCategoryShowName(positionAnalysis.getCategoryId());
            if (StringUtils.isNotEmpty(categoryName)) {
                categoryNames.add(categoryName);
                JSONObject o = new JSONObject();
                o.put("categoryName", categoryName);
                o.put("amount", positionAnalysis.getCompletedPaymentPageSum()
                        + positionAnalysis.getDetailPageSum()
                        + positionAnalysis.getFillOrderPageSum()
                        + positionAnalysis.getPendingPaymentPageSum());
                arr2.add(o);
            }
        }

        // 折线图数据
        String[] dateAxis = DateUtil.getBetweenTime(beginDate, endDate,
                "yyyy/MM/dd");
        List<String> dateList = Arrays.asList(dateAxis);
        JSONArray arr = new JSONArray();
        for (String date : dateList) {
            for (String category : categoryNames) {
                Integer amount = 0;
                for (PositionAnalysis position : pitListByDate) {
                    String categoryName = CommonParentType
                            .getCategoryShowName(position.getCategoryId());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    String time = sdf.format(position.getTime());
                    if (category.equals(categoryName) && date.equals(time)) {
                        amount += position.getCompletedPaymentPageSum()
                                + position.getDetailPageSum()
                                + position.getFillOrderPageSum()
                                + position.getPendingPaymentPageSum();
                    }
                }
                JSONObject o = new JSONObject();
                o.put("categoryName", category);
                o.put("time", date);
                o.put("amount", amount);
                arr.add(o);
            }
        }
        resultMap.put("payAmountTotal", payAmountTotal);
        resultMap.put("payMoneyTotal", payMoneyTotal);
        resultMap.put("jsonData", arr);
        resultMap.put("jsonData2", arr2);
        resultMap.put("payAmountJsonData", payAmountArr);
        resultMap.put("payMoneyJsonData", payMoneyArr);
        return resultMap;
    }

    /**
     * @param @param  chooseTime
     * @param @param  category_id
     * @param @return
     * @param @throws Exception 设定文件
     * @return Map<String,Object> 返回类型
     * @throws
     * @Title: getPageChartData
     * @Description: 根据品类获取相关页面的引流
     */
    @RequestMapping("getPageChartData")
    @ResponseBody
    public Map<String, Object> getPageChartData(
            @RequestParam("code") String code,
            @RequestParam("chooseTime") String chooseTime,
            @RequestParam("category_name") String category_name,String platform)
            throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        PositionAnalysis pit = new PositionAnalysis();
        // 查询日期条件处理
        Map<String, Date> dateMap = getQueryDate(chooseTime);
        Date beginDate = dateMap.get("beginDate");
        Date endDate = dateMap.get("endDate");
        pit.setStartDate(beginDate);
        pit.setEndDate(endDate);
        pit.setCode(code);
        if (StringUtils.isNotEmpty(platform)) {
            List<String> statisticCodeList = new ArrayList<String>();
            String[] platforms = StringUtils.split(platform,",");
            for(String pf:platforms){
                statisticCodeList.addAll(statisticCodeService.getDeviceCodeByLikeName(pf));
            }
            pit.setStatisticCodeList(statisticCodeList);
        }
        pit.setCategoryId(CommonParentType
                .getCategoryValueByShowName(category_name));
        PositionAnalysis pitForPage = positionAnalysisService
                .getPageNumByCategory(pit);
        resultMap.put("pitForPage", pitForPage);
        return resultMap;
    }

    /**
     * 查询专题漏斗数据
     *
     * @param query
     * @return
     */
    @RequestMapping("getTopicFunnel")
    @ResponseBody
    public List<SpecialTopicFunnelData> getTopicFunnel(TopicFunnelDataQuery query) {
        List<SpecialTopicFunnelData> funnelDataList = new ArrayList<>();
        try {
            funnelDataList = positionAnalysisService.getTopicFunnel(query);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return funnelDataList;
    }

    /**
     * @param @param  choose_date
     * @param @return 设定文件
     * @return Map<String,Date> 返回类型
     * @throws
     * @Title: getQueryDate
     * @Description: 查询条件起始时间的处理
     */
    private Map<String, Date> getQueryDate(String choose_date) {
        Map<String, Date> map = new HashMap<>();
        DateTimeFormatter formater = DateTimeFormat
                .forPattern("MM/dd/yyyy HH:mm:ss");
        Date beginDate = DateTime.parse(
                choose_date.split("-")[0].trim() + " 00:00:00", formater)
                .toDate();
        Date endDate = DateTime.parse(
                choose_date.split("-")[1].trim() + " 23:59:59", formater)
                .toDate();
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);
        return map;
    }

}
